"use client";

import { useState, useEffect } from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { ArrowUpDown, Trash2, Edit2 } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogClose,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";

interface Skill {
  id: string;
  name: string;
}

interface Course {
  id: string;
  name: string;
  skills: Skill[];
}

interface ScoreRecord {
  id: string;
  student: string;
  assignment: string;
  courseId: string;
  skillId: string;
  score: number;
  comment: string;
}

export function ScoreRecord() {
  const { t } = useLanguage();
  const [students, setStudents] = useState<string[]>([]);
  const [assignments, setAssignments] = useState<string[]>([]);
  const [courses, setCourses] = useState<Course[]>([]);
  const [scoreRecords, setScoreRecords] = useState<ScoreRecord[]>([]);

  const [selectedStudent, setSelectedStudent] = useState<string>("");
  const [selectedAssignment, setSelectedAssignment] = useState<string>("");
  const [selectedCourse, setSelectedCourse] = useState<string>("");
  const [selectedSkills, setSelectedSkills] = useState<string[]>([]);
  const [skillScores, setSkillScores] = useState<{ [key: string]: number }>({});
  const [skillComments, setSkillComments] = useState<{ [key: string]: string }>(
    {}
  );

  const [sortColumn, setSortColumn] = useState<keyof ScoreRecord | null>(null);
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");

  const [editingRecord, setEditingRecord] = useState<ScoreRecord | null>(null);
  const [editScore, setEditScore] = useState<number>(0);
  const [editComment, setEditComment] = useState<string>("");

  useEffect(() => {
    const savedStudents = JSON.parse(localStorage.getItem("students") || "[]");
    const savedAssignments = JSON.parse(
      localStorage.getItem("assignments") || "[]"
    );
    const savedCourses = JSON.parse(localStorage.getItem("courses") || "[]");
    const savedScoreRecords = JSON.parse(
      localStorage.getItem("scoreRecords") || "[]"
    );

    setStudents(savedStudents);
    setAssignments(savedAssignments);
    setCourses(savedCourses);
    setScoreRecords(savedScoreRecords);

    // Restore saved selections from localStorage
    const savedSelections = JSON.parse(
      localStorage.getItem("scoreRecordSelections") || "{}"
    );
    setSelectedStudent(savedSelections.student || "");
    setSelectedAssignment(savedSelections.assignment || "");
    setSelectedCourse(savedSelections.course || "");
    setSelectedSkills(savedSelections.skills || []);
    setSkillScores(savedSelections.skillScores || {});
    setSkillComments(savedSelections.skillComments || {});
  }, []);

  useEffect(() => {
    // Save selections to localStorage
    const selectionsToSave = {
      student: selectedStudent,
      assignment: selectedAssignment,
      course: selectedCourse,
      skills: selectedSkills,
      skillScores: skillScores,
      skillComments: skillComments,
    };
    localStorage.setItem(
      "scoreRecordSelections",
      JSON.stringify(selectionsToSave)
    );
  }, [
    selectedStudent,
    selectedAssignment,
    selectedCourse,
    selectedSkills,
    skillScores,
    skillComments,
  ]);

  const handleSkillToggle = (skillId: string) => {
    setSelectedSkills((prev) =>
      prev.includes(skillId)
        ? prev.filter((id) => id !== skillId)
        : [...prev, skillId]
    );
  };

  const handleScoreChange = (skillId: string, score: number) => {
    setSkillScores((prev) => ({
      ...prev,
      [skillId]: score,
    }));
  };

  const handleCommentChange = (skillId: string, comment: string) => {
    setSkillComments((prev) => ({
      ...prev,
      [skillId]: comment,
    }));
  };

  const isDuplicateScore = (
    student: string,
    assignment: string,
    skillId: string
  ) => {
    return scoreRecords.some(
      (record) =>
        record.student === student &&
        record.assignment === assignment &&
        record.skillId === skillId
    );
  };

  const handleSubmit = () => {
    if (
      selectedStudent &&
      selectedAssignment &&
      selectedCourse &&
      selectedSkills.length > 0
    ) {
      const newRecords: ScoreRecord[] = selectedSkills
        .map((skillId) => ({
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          student: selectedStudent,
          assignment: selectedAssignment,
          courseId: selectedCourse,
          skillId: skillId,
          score: skillScores[skillId] || 0,
          comment: skillComments[skillId] || "",
        }))
        .filter(
          (record) =>
            !isDuplicateScore(record.student, record.assignment, record.skillId)
        );

      if (newRecords.length === 0) {
        alert(t("所选技能已经被评分，请选择其他技能或作业。"));
        return;
      }

      const updatedRecords = [...scoreRecords, ...newRecords];
      setScoreRecords(updatedRecords);
      localStorage.setItem("scoreRecords", JSON.stringify(updatedRecords));

      // Reset only the skill scores, comments, and selections
      setSkillScores({});
      setSkillComments({});
      setSelectedSkills([]);
    }
  };

  const handleSort = (column: keyof ScoreRecord) => {
    if (sortColumn === column) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortColumn(column);
      setSortDirection("asc");
    }
  };

  const sortedRecords = [...scoreRecords].sort((a, b) => {
    if (!sortColumn) return 0;
    if (a[sortColumn] < b[sortColumn]) return sortDirection === "asc" ? -1 : 1;
    if (a[sortColumn] > b[sortColumn]) return sortDirection === "asc" ? 1 : -1;
    return 0;
  });

  const handleDelete = (id: string) => {
    if (window.confirm(t("确定要删除这条评分记录吗？"))) {
      const updatedRecords = scoreRecords.filter((record) => record.id !== id);
      setScoreRecords(updatedRecords);
      localStorage.setItem("scoreRecords", JSON.stringify(updatedRecords));
    }
  };

  const handleEdit = (record: ScoreRecord) => {
    setEditingRecord(record);
    setEditScore(record.score);
    setEditComment(record.comment);
  };

  const handleConfirmEdit = () => {
    if (editingRecord) {
      if (window.confirm(t("确定要修改这条评分记录吗？"))) {
        const updatedRecords = scoreRecords.map((record) =>
          record.id === editingRecord.id
            ? { ...record, score: editScore, comment: editComment }
            : record
        );
        setScoreRecords(updatedRecords);
        localStorage.setItem("scoreRecords", JSON.stringify(updatedRecords));
        setEditingRecord(null);
      }
    }
  };

  const exportData = () => {
    const dataStr = JSON.stringify(scoreRecords);
    const dataUri =
      "data:application/json;charset=utf-8," + encodeURIComponent(dataStr);
    const exportFileDefaultName = "score-records.json";
    const linkElement = document.createElement("a");
    linkElement.setAttribute("href", dataUri);
    linkElement.setAttribute("download", exportFileDefaultName);
    linkElement.click();
  };

  const importData = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result;
        if (typeof content === "string") {
          const importedScoreRecords = JSON.parse(content);
          setScoreRecords(importedScoreRecords);
          localStorage.setItem(
            "scoreRecords",
            JSON.stringify(importedScoreRecords)
          );
        }
      };
      reader.readAsText(file);
    }
  };

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold">{t("打分记录表")}</h2>
      <div className="flex justify-end space-x-2 mb-4">
        <Button onClick={exportData}>{t("导出")}</Button>
        <label htmlFor="import-file" className="cursor-pointer">
          <Input
            id="import-file"
            type="file"
            className="hidden"
            onChange={importData}
            accept=".json"
          />
          <Button>{t("导入")}</Button>
        </label>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Select value={selectedStudent} onValueChange={setSelectedStudent}>
          <SelectTrigger>
            <SelectValue placeholder={t("选择同学")} />
          </SelectTrigger>
          <SelectContent>
            {students.map((student) => (
              <SelectItem key={student} value={student}>
                {student}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select
          value={selectedAssignment}
          onValueChange={setSelectedAssignment}
        >
          <SelectTrigger>
            <SelectValue placeholder={t("选择作业")} />
          </SelectTrigger>
          <SelectContent>
            {assignments.map((assignment) => (
              <SelectItem key={assignment} value={assignment}>
                {assignment}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={selectedCourse} onValueChange={setSelectedCourse}>
          <SelectTrigger>
            <SelectValue placeholder={t("选择课程")} />
          </SelectTrigger>
          <SelectContent>
            {courses.map((course) => (
              <SelectItem key={course.id} value={course.id}>
                {course.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="space-y-2">
        <Label>{t("选择技能并评分（1-4分）")}</Label>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-h-60 overflow-y-auto">
          {courses
            .find((c) => c.id === selectedCourse)
            ?.skills.map((skill) => (
              <div key={skill.id} className="flex flex-col space-y-2">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id={skill.id}
                    checked={selectedSkills.includes(skill.id)}
                    onCheckedChange={() => handleSkillToggle(skill.id)}
                  />
                  <Label htmlFor={skill.id} className="flex-grow">
                    {skill.name}
                  </Label>
                  <Select
                    value={skillScores[skill.id]?.toString() || ""}
                    onValueChange={(value) =>
                      handleScoreChange(skill.id, parseInt(value))
                    }
                    disabled={!selectedSkills.includes(skill.id)}
                  >
                    <SelectTrigger className="w-20">
                      <SelectValue placeholder={t("评分")} />
                    </SelectTrigger>
                    <SelectContent>
                      {[1, 2, 3, 4].map((score) => (
                        <SelectItem key={score} value={score.toString()}>
                          {score}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <Textarea
                  placeholder={t("评语")}
                  value={skillComments[skill.id] || ""}
                  onChange={(e) =>
                    handleCommentChange(skill.id, e.target.value)
                  }
                  disabled={!selectedSkills.includes(skill.id)}
                />
              </div>
            ))}
        </div>
      </div>
      <Button onClick={handleSubmit}>{t("提交评分")}</Button>
      <div className="mt-8">
        <h3 className="text-xl font-semibold mb-4">{t("评分记录")}</h3>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead
                className="cursor-pointer"
                onClick={() => handleSort("student")}
              >
                {t("同学")}{" "}
                {sortColumn === "student" && (
                  <ArrowUpDown className="inline ml-2" />
                )}
              </TableHead>
              <TableHead
                className="cursor-pointer"
                onClick={() => handleSort("assignment")}
              >
                {t("作业")}{" "}
                {sortColumn === "assignment" && (
                  <ArrowUpDown className="inline ml-2" />
                )}
              </TableHead>
              <TableHead
                className="cursor-pointer"
                onClick={() => handleSort("courseId")}
              >
                {t("课程")}{" "}
                {sortColumn === "courseId" && (
                  <ArrowUpDown className="inline ml-2" />
                )}
              </TableHead>
              <TableHead
                className="cursor-pointer"
                onClick={() => handleSort("skillId")}
              >
                {t("技能")}{" "}
                {sortColumn === "skillId" && (
                  <ArrowUpDown className="inline ml-2" />
                )}
              </TableHead>
              <TableHead
                className="cursor-pointer"
                onClick={() => handleSort("score")}
              >
                {t("评分")}{" "}
                {sortColumn === "score" && (
                  <ArrowUpDown className="inline ml-2" />
                )}
              </TableHead>
              <TableHead>{t("评语")}</TableHead>
              <TableHead>{t("操作")}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedRecords.map((record) => (
              <TableRow key={record.id}>
                <TableCell>{record.student}</TableCell>
                <TableCell>{record.assignment}</TableCell>
                <TableCell>
                  {courses.find((c) => c.id === record.courseId)?.name}
                </TableCell>
                <TableCell>
                  {
                    courses
                      .find((c) => c.id === record.courseId)
                      ?.skills.find((s) => s.id === record.skillId)?.name
                  }
                </TableCell>
                <TableCell>{record.score}</TableCell>
                <TableCell>{record.comment}</TableCell>
                <TableCell>
                  <div className="flex space-x-2">
                    <Dialog>
                      <DialogTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEdit(record)}
                        >
                          <Edit2 className="h-4 w-4" />
                        </Button>
                      </DialogTrigger>
                      <DialogContent>
                        <DialogHeader>
                          <DialogTitle>{t("修改评分")}</DialogTitle>
                        </DialogHeader>
                        <div className="py-4 space-y-4">
                          <div>
                            <Label htmlFor="edit-score">{t("新评分")}</Label>
                            <Select
                              value={editScore.toString()}
                              onValueChange={(value) =>
                                setEditScore(parseInt(value))
                              }
                            >
                              <SelectTrigger className="w-full">
                                <SelectValue placeholder={t("选择新评分")} />
                              </SelectTrigger>
                              <SelectContent>
                                {[1, 2, 3, 4].map((score) => (
                                  <SelectItem
                                    key={score}
                                    value={score.toString()}
                                  >
                                    {score}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                          <div>
                            <Label htmlFor="edit-comment">{t("新评语")}</Label>
                            <Textarea
                              id="edit-comment"
                              value={editComment}
                              onChange={(e) => setEditComment(e.target.value)}
                              placeholder={t("输入新评语")}
                            />
                          </div>
                        </div>
                        <DialogClose asChild>
                          <Button onClick={handleConfirmEdit}>
                            {t("确认修改")}
                          </Button>
                        </DialogClose>
                      </DialogContent>
                    </Dialog>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleDelete(record.id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
